package org.tamal.jsf;

import java.io.IOException;

import javax.faces.application.Application;
import javax.faces.application.NavigationHandler;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

import org.tamal.Constants;
import org.tamal.SessionKey;

import com.google.appengine.api.datastore.Entity;

/**
 * This listener redirects to login page if the user is not logged in.
 * @author Tamal Kanti Nath
 */
public final class AuthenticationListener implements PhaseListener {

    private static final long serialVersionUID = -8938736370598958565L;
    private static final String LOGIN = "/login.xhtml";
    private static final String ERROR = "/WEB-INF/content/error.xhtml";

    /**
     * This method returns silently if the user is logged in or the page being
     * viewed is the login page. Otherwise, it will redirect to the login page.
     */
    @Override
    public void afterPhase(PhaseEvent event) {
		if (!Constants.PRODUCTION) {
			return;
		}
        FacesContext context = event.getFacesContext();
        ExternalContext ext = context.getExternalContext();
        Entity user = (Entity) ext.getSessionMap().get(SessionKey.USER);
        String view = context.getViewRoot().getViewId();
        if (user != null || LOGIN.equals(view) || ERROR.equals(view)) {
            return;
        }
        ext.getSessionMap().put(SessionKey.REDIRECT.name(), view);
        try {
            ext.redirect(LOGIN);
        } catch (IOException e) {
            Application application = context.getApplication();
            NavigationHandler navigation = application.getNavigationHandler();
            navigation.handleNavigation(context, null, "login");
        }
    }

    @Override
    public void beforePhase(PhaseEvent event) {
        // Empty
    }

    @Override
    public PhaseId getPhaseId() {
        return PhaseId.RESTORE_VIEW;
    }

}
